package com.hzf.booklibrary.okhttp;

import android.os.Handler;
import android.os.Looper;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/8/1.
 */

public class OkHttpManager {
    private static OkHttpManager mInstance;
    private  OkHttpClient okHttpClient;
    private  Handler mDelivery;
    public static OkHttpManager getInstance(){
        if(mInstance==null){
            synchronized (OkHttpManager.class){
                mInstance=new OkHttpManager();
            }
        }
        return mInstance;
    }
    private OkHttpManager(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(30000, TimeUnit.MILLISECONDS)
        .readTimeout(30000, TimeUnit.MILLISECONDS)
        .writeTimeout(30000, TimeUnit.MILLISECONDS);
        okHttpClient = builder.build();

        mDelivery = new Handler(Looper.getMainLooper());
    }

    public void postAsyn(String url, Map<String,String> params,ResultCallBack callBack){
        Request request = buildPostFormRequest(url,params);
        deliveryResult(request,callBack);
    }
    public void getAsyn(String url,ResultCallBack callBack){
        Request request = buildPostFormRequest(url,null);
        deliveryResult(request,callBack);
    }


    private  void deliveryResult(final Request request, ResultCallBack callBack) {
        if(callBack==null){

        }
      final ResultCallBack resultCallBack = callBack;
       callBack.onBefore(request);
       okHttpClient.newCall(request).enqueue(new Callback() {
           @Override
           public void onFailure(Call call, final IOException e) {
               mDelivery.post(new Runnable() {
                   @Override
                   public void run() {
                       resultCallBack.onError(request,e);
                   }
               });
           }

           @Override
           public void onResponse(Call call, final Response response) throws IOException {
               final String result = response.body().string();
                mDelivery.post(new Runnable() {
                    @Override
                    public void run() {
                        resultCallBack.onResponse(result);
                        resultCallBack.onAfter();
                    }
                });
           }
       });
    }

    private static Request buildPostFormRequest(String url, Map<String,String> params){
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if(params!=null){
            for (Map.Entry<String,String> entry:params.entrySet()){
                builder.addHeader(entry.getKey(),entry.getValue());
            }
        }
        return builder.build();
    }
}
